var MBUSS = {
	map: null,
	terminalOrigem: null,
	terminalDestino: null,
	geocoder: new google.maps.Geocoder(),
	directionsRenderer: new google.maps.DirectionsRenderer({
            markerOptions: {
                visible: false,
                draggable: false
            }
        }),
        busMarkers: [],
        stopMarkers: {},
        infoWindows: {},
	init: function() {
		var latlng = new google.maps.LatLng(-23.6014, -46.6758);

		var mapOptions = {
		  zoom: 15,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		}

		MBUSS.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	},
        view: function() {
            var linhaId = $('linhaId').getValue();

            new Ajax.Request('View.action', {
                parameters: {
                    linhaId: linhaId
                },
                onSuccess: function(transport) {
                    var response = transport.responseJSON;
                    var linha = response.linha;

                    var openInfoWindow = function(title) {
                        var pontoId = MBUSS.stopMarkers[title].pontoId;
                        var marker = MBUSS.stopMarkers[title];
                        if (MBUSS.infoWindows.pontoId != undefined) {
                            MBUSS.infoWindows.pontoId.close();
                            MBUSS.infoWindows.pontoId = undefined;
                        }
                        var linhaId = $('linhaId').getValue();
                        var infoWindow = new google.maps.InfoWindow({
                            content: 'loading...'
                        });
                        infoWindow.open(MBUSS.map, marker);
                        MBUSS.infoWindows.pontoId = infoWindow;

                        new Ajax.Request('Consulta.action', {
                            parameters: {
                                op: 'estimativa',
                                linhaId: linhaId,
                                pontoId: pontoId
                            },
                            onSuccess: function(transport) {
                                infoWindow.setContent(transport.responseText);
                            }
                        });
                    };

                    var origin = new google.maps.Marker({
                        clickable: true,
                        map: MBUSS.map,
                        position: new google.maps.LatLng(linha.origin.lat, linha.origin.lng),
                        title: linha.origin.nome,
                        icon: new google.maps.MarkerImage("http://186.204.38.174:8080/sismol/images/ponto.png")
                    });
                    origin.pontoId = linha.origin.id;
                    MBUSS.stopMarkers[linha.origin.nome] = origin;
                    google.maps.event.addListener(origin, 'click', function() {
                        openInfoWindow(linha.origin.nome);
                    }.bind(this));

                    var destination = new google.maps.Marker({
                        clickable: true,
                        map: MBUSS.map,
                        position: new google.maps.LatLng(linha.destination.lat, linha.destination.lng),
                        title: linha.destination.nome,
                        icon: new google.maps.MarkerImage("http://186.204.38.174:8080/sismol/images/ponto.png")
                    });
                    destination.pontoId = linha.destination.id;
                    MBUSS.stopMarkers[linha.destination.nome] = destination;
                    google.maps.event.addListener(destination, 'click', function() {
                        openInfoWindow(linha.destination.nome);
                    }.bind(this));

                    var waypoints = [];
                    for (var i = 0; i<linha.waypoints.length; i++) {
                        (function(i) {
                            var ponto = linha.waypoints[i];
                            var latlng = new google.maps.LatLng(ponto.lat, ponto.lng);
                            var point = {
                                location: latlng,
                                stopover: ponto.parada
                            };

                            var marker = new google.maps.Marker({
                                clickable: true,
                                map: MBUSS.map,
                                position: latlng,
                                title: ponto.nome,
                                icon: new google.maps.MarkerImage("http://186.204.38.174:8080/sismol/images/ponto.png")
                            });
                            marker.pontoId = ponto.id;
                            MBUSS.stopMarkers[ponto.nome] = marker;
                            google.maps.event.addListener(MBUSS.stopMarkers[ponto.nome], 'click', function(e) {
                                openInfoWindow(ponto.nome);
                            }.bind(this));

                            waypoints.push(point);
                        })(i);
                    }

                    var directions = new google.maps.DirectionsService();

                    var directionsRequest = {
                            origin: new google.maps.LatLng(linha.origin.lat, linha.origin.lng),
                            destination: new google.maps.LatLng(linha.destination.lat, linha.destination.lng),
                            travelMode: google.maps.DirectionsTravelMode.DRIVING,
                            provideRouteAlternatives: false,
                            waypoints: waypoints
                    }
                    directions.route(directionsRequest, function(result, status){
                            MBUSS.directionsRenderer.setMap(MBUSS.map);
                            MBUSS.directionsRenderer.setDirections(result);
                    });

                    // Exibe posição dos ônibus.
                    var list = response.onibus;
                    MBUSS.mostraOnibus(list);
                }
            });

            MBUSS.refreshOnibus();
        },

        refreshOnibus: function() {
            var linhaId = $('linhaId').getValue();

            new Ajax.Request('View.action', {
                parameters: {
                    linhaId: linhaId
                },
                onSuccess: function(transport) {
                    var response = transport.responseJSON;
                    var list = response.onibus;
                    MBUSS.mostraOnibus(list);
                }
            });

            setTimeout("MBUSS.refreshOnibus();",15000);
        },

        mostraOnibus: function(list) {
            if (MBUSS.busMarkers.length > 0) {
                for (var i = 0; i < MBUSS.busMarkers.length; i++) {
                    MBUSS.busMarkers[i].setVisible(false);
                }
            }
            MBUSS.busMarkers = [];

            for(i = 0; i < list.length; i++) {
                var onibus = list[i];

                var marker = new google.maps.Marker({
                    clickable: true,
                    map: MBUSS.map,
                    position: new google.maps.LatLng(onibus.lat, onibus.lng),
                    icon: new google.maps.MarkerImage("http://186.204.38.174:8080/sismol/images/onibus.png")
                });
                MBUSS.busMarkers.push(marker);
            }
        },

        toogleInstructions: function(title) {
            if ($('instrucoes').visible()) {
                Effect.SlideUp('instrucoes', {
                    duration: 0.5
                });
                title.down('img').src='images/expand.png';
            } else {
                Effect.SlideDown('instrucoes', {
                    duration: 0.5
                });
                title.down('img').src='images/collapse.png';
            }
        }
    }

